package com.botarena.client;

import java.util.logging.Logger;

import com.botarena.client.account.AccountViewer;
import com.botarena.client.account.remote.AccountAccess;
import com.botarena.client.account.remote.AccountAccessAsync;
import com.botarena.shared.UserInfo;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

public class BotArena implements EntryPoint {
	
	private static final Logger log = Logger.getLogger(BotArena.class.getName());

	public void onModuleLoad() {
		RootPanel.get("content").add(UIHelper.createSmallLoader("loading..."));
		RootPanel.get("rightMenu").add(UIHelper.createSmallLoader(""));

		AccountAccessAsync loginService = GWT.create(AccountAccess.class);
		AsyncCallback<UserInfo> callback = new AsyncCallback<UserInfo>() {

			public void onFailure(Throwable caught) {
				clear();
				handleError(caught);
			}

			public void onSuccess(UserInfo result) {
				clear();
				main(result);
			}
			
			private void clear() {
				RootPanel.get("content").clear();
				RootPanel.get("rightMenu").clear();				
			}
		};
		loginService.getUserInfo(GWT.getHostPageBaseURL(), callback);
	}

	private void main(final UserInfo userInfo) {
		log.info("UserInfo: " + userInfo.toString());
		
		RootPanel.get("topMenu").add(MenuViewer.createMainMenuPanel(userInfo));
		RootPanel.get("accountInfo")
				.add(AccountViewer.createAccountBar(userInfo));
		//RootPanel.get("lastBattlesContainer").add(createLastBattlesPanel(8));

		final RightMenu rightMenu = MenuViewer.createRightMenuPanel(userInfo);
		RootPanel.get("rightMenu").add(rightMenu);
		
		String locationToken = Location.getHash();
		if(!locationToken.equals(""))
			locationToken = locationToken.substring(1);
		ContentManager.changeSiteContent(locationToken, userInfo, rightMenu);
		
		History.addValueChangeHandler(new ValueChangeHandler<String>() {
			
			@Override
			public void onValueChange(ValueChangeEvent<String> event) {
				
				String token = History.getToken();
				log.info(token);
				ContentManager.changeSiteContent(token, userInfo, rightMenu);
			}
			
		});
		
	}

	private void handleError(Throwable error) {
		RootPanel.get("content").add(
				new Label("ERROR: " + error.toString()));
	}

}
